﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AttachScreenShotToJira.CODE.CORE_LOGIC
{
    class GREENSHOT_HANDLING
    {
        //get if the application is installed
        public static string getGreenShotPathIni()
        {
            try
            {
                List<string> folders = Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).ToList();

                foreach (string folder in folders)
                {
                    if (folder.ToLower().Contains("greenshot"))
                    {
                        return Path.Combine(folder, "Greenshot.ini");
                    }
                }

                return "";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to get Greenshot ini path. Reason: "+ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "";
            }
        }

        //was the content added?
        public static bool AlreadyInGreenshot()
        {
            try
            {
                string[] lines = System.IO.File.ReadAllLines(Properties.Settings.Default.sGreenshotINI);

                var query = from element in lines
                            where element.Contains("AttachToJira")
                            select element;

                return query.Count() > 0 ? true : false;
            }
            catch
            {
                return false;
            }
        }

        private static string read_ini_header(string inifile)
        {
            try
            { 
                string[] lines = System.IO.File.ReadAllLines(inifile);

                string ini_content = "";

                bool sec_break = false;

                foreach (string line in lines)
                {
                    //search for break
                    if (line == "[ExternalCommand]")
                    {
                        sec_break = true;
                        ini_content += line + Environment.NewLine + "; The commands that are available." + Environment.NewLine;
                    }

                    //as long as not found, add text
                    if (!sec_break)
                        ini_content += line + Environment.NewLine;
                }

                return ini_content;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to load Greenshot ini header. Reason: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "";
            }
        }

        private static string read_ini_footer(string inifile)
        {
            try
            {
                string[] lines = System.IO.File.ReadAllLines(inifile);

                string ini_content = "";

                bool headerfound = false;
                bool footersection = false;

                foreach (string line in lines)
                {
                    //as long as not found, add text
                    if (line.Contains("[") && headerfound)
                        footersection = true;

                    //search for break
                    if (line == "[ExternalCommand]")
                        headerfound = true;

                    if (footersection)
                        ini_content += line + Environment.NewLine;
                }

                return ini_content;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to load Greenshot ini footer. Reason: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "";
            }
        }

        public static bool handleStatusinGreenShot(bool display, string pathtoiniFile)
        {
            try
            {
                if (MANAGE_PROCESSES.stopGreenshot())
                {
                    //set the header
                    string inicontent = read_ini_header(pathtoiniFile);
                    if (display)
                    {
                        inicontent += addJIRAtoGreenshot();
                    }
                    else
                    {
                        inicontent += removeJIRAfromGreenshot();
                    }
                    //set the footer
                    inicontent += read_ini_footer(pathtoiniFile);

                    System.IO.File.WriteAllText(pathtoiniFile, inicontent);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to update Greenshot Ini. Reason: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        private static string addJIRAtoGreenshot()
        {
            string content = "Commands=MS Paint,AttachToJira" + Environment.NewLine;
            content += "; Redirect the standard error of all external commands, used to output as warning to the greenshot.log." + Environment.NewLine;
            content += "RedirectStandardError=True" + Environment.NewLine;
            content += "; Redirect the standard output of all external commands, used for different other functions (more below)." + Environment.NewLine;
            content += "RedirectStandardOutput=True" + Environment.NewLine;
            content += "; Depends on 'RedirectStandardOutput': Show standard output of all external commands to the Greenshot log, this can be usefull for debugging." + Environment.NewLine;
            content += "ShowStandardOutputInLog=False" + Environment.NewLine;
            content += "; Depends on 'RedirectStandardOutput': Parse the output and take the first found URI, if a URI is found than clicking on the notify bubble goes there." + Environment.NewLine;
            content += "ParseForUri=True" + Environment.NewLine;
            content += "; Depends on 'RedirectStandardOutput': Place the standard output on the clipboard." + Environment.NewLine;
            content += "OutputToClipboard=False" + Environment.NewLine;
            content += "; Depends on 'RedirectStandardOutput' & 'ParseForUri': If an URI is found in the standard input, place it on the clipboard. (This overwrites the output from OutputToClipboard setting.)" + Environment.NewLine;
            content += "UriToClipboard=True" + Environment.NewLine;
            content += ";The commandline for the output command." + Environment.NewLine;
            content += "Commandline.MS Paint=C:\\Windows\\System32\\mspaint.exe" + Environment.NewLine;
            content += "Commandline.AttachToJira=" + System.Reflection.Assembly.GetExecutingAssembly().Location + Environment.NewLine;
            content += "; The arguments for the output command." + Environment.NewLine;
            content += "Argument.MS Paint=\"{0}\"" + Environment.NewLine;
            content += "Argument.AttachToJira=\"{0}\"" + Environment.NewLine;
            content += "; Should the command be started in the background." + Environment.NewLine;
            content += "RunInbackground.MS Paint=True" + Environment.NewLine;
            content += "RunInbackground.AttachToJira=True" + Environment.NewLine + Environment.NewLine;

            return content;
        }

        private static string removeJIRAfromGreenshot()
        {
            string content = "Commands=MS Paint" + Environment.NewLine;
            content += "; Redirect the standard error of all external commands, used to output as warning to the greenshot.log." + Environment.NewLine;
            content += "RedirectStandardError=True" + Environment.NewLine;
            content += "; Redirect the standard output of all external commands, used for different other functions (more below)." + Environment.NewLine;
            content += "RedirectStandardOutput=True" + Environment.NewLine;
            content += "; Depends on 'RedirectStandardOutput': Show standard output of all external commands to the Greenshot log, this can be usefull for debugging." + Environment.NewLine;
            content += "ShowStandardOutputInLog=False" + Environment.NewLine;
            content += "; Depends on 'RedirectStandardOutput': Parse the output and take the first found URI, if a URI is found than clicking on the notify bubble goes there." + Environment.NewLine;
            content += "ParseForUri=True" + Environment.NewLine;
            content += "; Depends on 'RedirectStandardOutput': Place the standard output on the clipboard." + Environment.NewLine;
            content += "OutputToClipboard=False" + Environment.NewLine;
            content += "; Depends on 'RedirectStandardOutput' & 'ParseForUri': If an URI is found in the standard input, place it on the clipboard. (This overwrites the output from OutputToClipboard setting.)" + Environment.NewLine;
            content += "UriToClipboard=True" + Environment.NewLine;
            content += ";The commandline for the output command." + Environment.NewLine;
            content += "Commandline.MS Paint=C:\\Windows\\System32\\mspaint.exe" + Environment.NewLine;
            content += "; The arguments for the output command." + Environment.NewLine;
            content += "Argument.MS Paint=\"{0}\"" + Environment.NewLine;
            content += "; Should the command be started in the background." + Environment.NewLine;
            content += "RunInbackground.MS Paint=True" + Environment.NewLine;

            return content;
        }
    }
}
